var data;
var basicdata;
var display_level = ['', 'easy', 'medium', 'hard', 'random'];
// dynamically modify the title
function getName() {
    let title = document.getElementById("title2");
    title.innerHTML = 'Quiz Record of ' + localStorage.getItem("UserName") + "<br>" + " Test time:" +  basicdata[0].hdate;
}
// generate quiz history form
function getTable() {
    let htmlStr = "";

    let detail = basicdata[0];
    htmlStr += "<tr>";
    htmlStr += "<td>" + detail.hdate + "</td>";
    htmlStr += "<td>" + detail.hcategory + "</td>";
    htmlStr += "<td>" + display_level[detail.hlevel] + "</td>";
    htmlStr += "<td>" + detail.hsize + "</td>";
    if (5 <= detail.htimelimit && detail.htimelimit <= 20) {
        htmlStr += "<td>" + detail.htimelimit + "</td>";
    } else {
        htmlStr += "<td>" + "No time limit" + "</td>";
    }
    htmlStr += "<td>" + detail.hscore + "</td>";
    htmlStr += "</tr>";

    document.getElementById("tBody").innerHTML = htmlStr;
}
// get quiz detail 
function getOtherInformation() {
    let htmlStr = "";
    for (var i in data) {
        htmlStr += "<tr>";
        htmlStr += "<td>" + data[i].dquestion + "</td>";
        htmlStr += "<td>" + data[i].danswer + "</td>";
        if(data[i].dstate == 'Wrong answer'){
            htmlStr += "<td style=\"color: red;\">" + data[i].dstate + "</td>";
        }else{
            htmlStr += "<td style=\"color: orange;\">" + data[i].dstate + "</td>";
        }
        // htmlStr += "<td>" + data[i].dstate + "</td
        htmlStr += "</tr>";
    }
    document.getElementById("tBody2").innerHTML = htmlStr;
}
window.onload = function () {
    // modify header
    function isLogin(){
        if(localStorage.hasOwnProperty("UserName")){
            document.getElementById("login").style.display = 'none';
            document.getElementById("login-out").style.display = 'block';
            document.getElementById("profile").style.display = 'block';
            document.querySelector("#profile a").innerHTML = 'User: ' + localStorage.getItem('UserName');
        }
        else{
            document.getElementById("login-out").style.display = 'none';
            document.getElementById("login").style.display = 'block';
            document.getElementById("profile").style.display = 'none';
        }
    }
    isLogin();

    function ok() {
        console.log(this.responseText);
        let json_object = JSON.parse(this.responseText);
        basicdata = json_object.basic;
        data = json_object.detail;
        getName();
        getTable();
        getOtherInformation();
    }
    function ko() {
        console.log(this.responseText);
    }
    var params = new URLSearchParams();
    params.append('datetime', localStorage.getItem('hdate'));
    var url = '../php/getdetail.php?' + params.toString();
    ajaxRequest(url, 'get', null, ok, ko);
}